package com.pysoft.safe.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.pysoft.common.util.Identities;
import com.pysoft.safe.dao.entity.ResourceEntity;
import com.pysoft.safe.dao.mapper.ResourceMapper;
import com.pysoft.safe.dao.mapper.RoleResourceMapper;
import com.pysoft.safe.service.ResourceService;

public class ResourceServiceImpl implements ResourceService {

	private ResourceMapper resourceDao;
	private RoleResourceMapper roleResourceDao;
	
	public RoleResourceMapper getRoleResourceDao() {
		return roleResourceDao;
	}

	public void setRoleResourceDao(RoleResourceMapper roleResourceDao) {
		this.roleResourceDao = roleResourceDao;
	}

	public ResourceMapper getResourceDao() {
		return resourceDao;
	}

	public void setResourceDao(ResourceMapper resourceDao) {
		this.resourceDao = resourceDao;
	}

	@Override
	public List<ResourceEntity> query(Map<String, Object> paramMap) {
		return this.getResourceDao().query(paramMap);
	}

	@Override
	public ResourceEntity getResource(String id) {
		return this.getResourceDao().get(id);
	}

	@Override
	public ResourceEntity addResource(ResourceEntity resource) {
		String id = Identities.uuid2();
		ResourceEntity entity = new ResourceEntity();
		entity.setId(id);
		entity.setPid(resource.getPid());
		entity.setCode(id);
		entity.setName(id);
		entity.setTitle(id);
		entity.setEnable("1");
		entity.setTarget("main");
		entity.setType(resource.getType());
		entity.setIcon(resource.getIcon());
		this.getResourceDao().insert(entity);
		return entity;
	}

	@Override
	public void modifyResource(ResourceEntity resource) {
		this.getResourceDao().update(resource);
	}

	@Override
	public void removeResource(String id) {
		this.getResourceDao().delete(id);
	}

	@Override
	public void relatingRole(String resourceId, List<String> roleIdList) {
		roleResourceDao.deleteByResource(resourceId);
		Map<String, Object> entity = null;
		for(String roleId:roleIdList) {
			entity = new HashMap<String, Object>();
			entity.put("roleId", roleId);
			entity.put("resourceId", resourceId);
			roleResourceDao.insert(entity);
		}
	}
	
	@Override
	public void cancelRelatingRole(String resourceId) {
		roleResourceDao.deleteByResource(resourceId);
	}
	
	@Override
	public List<String> getRelatingRoles(String resourceId) {
		return roleResourceDao.queryRole(resourceId);
	}
}
